//
//  MHComicPictureViewController.m
//  ManHua
//
//  Created by 赵永泉 on 15/10/26.
//  Copyright © 2015年 蓝欧科技. All rights reserved.
//

#import "MHComicPictureViewController.h"
#import "MHComicPictureCell.h"
#import "MHComicSystemView.h"
#import "UIImage+Addiction.h"
#import "MBProgressHUD+MJ.h"
#import "MHPisctureHeight.h"
#import "MHPopView.h"
#import "MHDataManager.h"
#import <AFNetworking.h>

@interface MHComicPictureViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>
@property (nonatomic, strong) MHComicEpisode *episode;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *pictureURLArray;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, assign) CGFloat tableViewScrollHeight;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, assign) CGFloat assistViewHeight;
@property (nonatomic, strong) UIView *systemView;
@property (nonatomic, strong) MHComicSystemView *comicSystemView;
@property (nonatomic, strong) UILabel *SectionName;
@property (nonatomic, strong) UISlider *progressSlider;
@property (nonatomic, strong) NSMutableArray *previousArray;
@property (nonatomic, strong) NSMutableArray *nextArray;
@property (nonatomic, assign) CGFloat newy;
@property (nonatomic, assign) CGFloat oldy;
@property (nonatomic, assign) BOOL isautoScroll;
@property (nonatomic, assign) BOOL isAutoPageUp;
@property (nonatomic, assign) BOOL isDownload;
@property (nonatomic, assign) BOOL isShowFirstPage;
@property (nonatomic, assign) BOOL isShowLastPage;
@property (nonatomic, strong) MHPopView *popView;

@end

@implementation MHComicPictureViewController

- (NSMutableArray *)pictureURLArray
{
    if (_pictureURLArray == nil) {
        _pictureURLArray = [NSMutableArray array];
    }
    return _pictureURLArray;
}

- (NSMutableArray *)previousArray
{
    if (_previousArray == nil) {
        _previousArray = [NSMutableArray array];
    }
    return _previousArray;
}

- (NSMutableArray *)nextArray
{
    if (_nextArray == nil) {
        _nextArray = [NSMutableArray array];
    }
    return _nextArray;
}

- (void)setEpisode:(MHComicEpisode *)episode
{
    if (_episode == nil) {
        if (episode.resource_id == 0) {
            [self acquirePictureWith:episode];
        }
        else
        {
            [self acquireKonPictureWith:episode];
        }
    }
    _episode = episode;
}

- (void)acquirePictureWith:(MHComicEpisode *)episode
{
    NSDictionary *dict = [NSDictionary dictionaryWithObjects:@[@"picturelist", [NSString stringWithFormat:@"%ld", (long)episode.SectionID]] forKeys:@[@"method", @"sectionid"]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperationManager manager] GET:@"http://112.124.96.190:9090/bukamanhua5appjobs/ComicHandle.ashx" parameters:dict success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        __weak MHComicPictureViewController *test = self;
        if (self.index != 0 && [self.episodeArray[self.index - 1] isEqual:episode]) {
            for (NSDictionary *dict in responseObject) {
                MHPisctureHeight *height = [[MHPisctureHeight alloc]initWithPictureUrl:dict[@"PictureURL"]];
                height.reloadCellBlock = ^()
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [test.tableView reloadData];
                    });
                };
                [self.nextArray addObject:height];
            }
        }
        if ([self.episodeArray[self.index] isEqual:episode]){
            for (NSDictionary *dict in responseObject) {
                MHPisctureHeight *height = [[MHPisctureHeight alloc]initWithPictureUrl:dict[@"PictureURL"]];
                height.reloadCellBlock = ^()
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [test.tableView reloadData];
                    });
                };
                [self.pictureURLArray addObject:height];
            }
        }
        if (self.index != self.episodeArray.count - 1 && [self.episodeArray[self.index + 1] isEqual:episode])
        {
            for (NSDictionary *dict in responseObject) {
                MHPisctureHeight *height = [[MHPisctureHeight alloc]initWithPictureUrl:dict[@"PictureURL"]];
                height.reloadCellBlock = ^()
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [test.tableView reloadData];
                    });
                };
                [self.previousArray addObject:height];
            }
        }
        self.isDownload = NO;
        [self.tableView reloadData];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.popView removeFromSuperview];
        });
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@", error.localizedDescription);
    }];
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        [self.popView changeProgressValue:((float)totalBytesRead / (float)totalBytesExpectedToRead)];
    }];
}

- (void)acquireKonPictureWith:(MHComicEpisode *)episode
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    AFHTTPRequestOperation *operation = [manager GET:[NSString stringWithFormat:@"https://bone.comikon.net/v8.3/resources/%ld/serial/%ld/slides/", (long)episode.resource_id, (long)episode.sid] parameters:[NSDictionary dictionaryWithObjects:@[@"json"] forKeys:@[@"format"]] success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        __weak MHComicPictureViewController *test = self;
        NSString *prefix = responseObject[@"prefix"];
        if (self.index != 0 && [self.episodeArray[self.index - 1] isEqual:episode]) {
            for (NSDictionary *dict in responseObject[@"slides"]) {
                MHPisctureHeight *height = [[MHPisctureHeight alloc]initWithPictureUrl:[NSString stringWithFormat:@"%@%@", prefix, dict[@"slide_url"]]];
                height.reloadCellBlock = ^()
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [test.tableView reloadData];
                    });
                };
                [self.nextArray addObject:height];
            }
        }
        if ([self.episodeArray[self.index] isEqual:episode]){
            for (NSDictionary *dict in responseObject[@"slides"]) {
                MHPisctureHeight *height = [[MHPisctureHeight alloc]initWithPictureUrl:[NSString stringWithFormat:@"%@%@", prefix, dict[@"slide_url"]]];
                height.reloadCellBlock = ^()
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [test.tableView reloadData];
                    });
                };
                [self.pictureURLArray  addObject:height];
            }
        }
        if (self.index != self.episodeArray.count - 1 && [self.episodeArray[self.index + 1] isEqual:episode])
        {
            for (NSDictionary *dict in responseObject[@"slides"]) {
                MHPisctureHeight *height = [[MHPisctureHeight alloc]initWithPictureUrl:[NSString stringWithFormat:@"%@%@", prefix, dict[@"slide_url"]]];
                height.reloadCellBlock = ^()
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [test.tableView reloadData];
                    });
                };
                [self.previousArray  addObject:height];
            }
        }
        self.isDownload = NO;
        [self.tableView reloadData];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.popView removeFromSuperview];
        });    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@", error.localizedDescription);
    }];
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        [self.popView changeProgressValue:((float)totalBytesRead / (float)totalBytesExpectedToRead)];
    }];
}


- (void)setEpisodeArray:(NSArray *)episodeArray
{
    _episodeArray = episodeArray;
    self.episode = episodeArray[self.index];
    if (self.index != 0) {
        MHComicEpisode *episode = episodeArray[self.index - 1];
        if (episode.resource_id == 0) {
            [self acquirePictureWith:episode];
        }
        else
        {
            [self acquireKonPictureWith:episode];
        }
    }
    if (self.index != episodeArray.count - 1)
    {
        MHComicEpisode *episode = episodeArray[self.index + 1];
        if (episode.resource_id == 0) {
            [self acquirePictureWith:episode];
        }
        else
        {
            [self acquireKonPictureWith:episode];
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =[UIColor whiteColor];
    self.isAutoPageUp = YES;
    [self addProgressView];


    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, Height, Width)];
    self.scrollView.maximumZoomScale = 2;
    self.scrollView.minimumZoomScale = 1;
    self.scrollView.delegate = self;
    self.scrollView.transform = CGAffineTransformMakeRotation(-M_PI / 2);
    self.scrollView.center = CGPointMake(Width * 0.5, Height * 0.5);
    [self.view addSubview:self.scrollView];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Height, Width)];
    [self.scrollView addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[MHComicPictureCell class] forCellReuseIdentifier:@"picture"];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(isAllowPageUp:) name:@"isAllowPageUp" object:nil];
    [self addSystemView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showAssistView)];
    [self.view addGestureRecognizer:tap];

    [self.view bringSubviewToFront:self.popView];
    [self addTopView];
    [self addBottomView];
}

- (void)addProgressView
{
    
    self.popView = [[MHPopView alloc]init];
    self.popView.frame = self.view.bounds;
    self.popView.transform = CGAffineTransformMakeRotation(-M_PI / 2);
    self.popView.center = CGPointMake(Height * 0.5, Width * 0.9);
    self.popView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:self.popView];
}

- (void)isAllowPageUp:(NSNotification *)notification
{
    self.isAutoPageUp = [notification.userInfo[@"switchState"] boolValue];
}

- (void)addSystemView
{
    MHComicSystemView *view = [[MHComicSystemView alloc]init];
    self.comicSystemView = view;
    view.episodeName = self.episode.SectionName;
    view.totalPage = self.episode.PicCount;
    [self.view addSubview:view.systemView];
    
}

- (void)addTopView
{
    self.assistViewHeight = Width * 0.15;
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Height, self.assistViewHeight)];
    topView.backgroundColor = [UIColor blackColor];
    topView.alpha = 0.7f;
    [self.view addSubview:topView];
    topView.transform = CGAffineTransformMakeRotation(-M_PI / 2);
    topView.center = CGPointMake(topView.frame.size.width * 0.5, topView.frame.size.height * 0.5);
    self.topView = topView;
    
    CGFloat margin = 20;
    
    UIButton *button = [[UIButton alloc]init];
    CGFloat buttonW = 20;
    CGFloat buttonX = (topView.frame.size.width - buttonW) / 2 + 5;
    button.frame = CGRectMake(buttonX, buttonX, buttonW, buttonW);
    [button setImage:[UIImage imageNamed:@"iconfont-fanhui-1"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backPreviousVC) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:button];
    
    CGFloat labelX = CGRectGetMaxX(button.frame) + margin;
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(labelX, buttonX, topView.frame.size.height - 2 * labelX, buttonW)];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = self.episode.SectionName;
    [self.topView addSubview:titleLabel];
    self.SectionName = titleLabel;
    
    
}

- (void)addBottomView
{
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Height, self.assistViewHeight)];
    bottomView.backgroundColor = [UIColor blackColor];
    bottomView.alpha = 0.7f;
    [self.view addSubview:bottomView];
    bottomView.transform = CGAffineTransformMakeRotation(-M_PI / 2);
    bottomView.center = CGPointMake(Width - bottomView.frame.size.width * 0.5, bottomView.frame.size.height * 0.5);
    self.bottomView = bottomView;
    
    CGFloat margin = 20;
    CGFloat sliderH = 20;
    CGFloat sliderX = (bottomView.frame.size.width - sliderH) / 2;
    CGFloat sliderW = bottomView.frame.size.height * 0.3;
    UISlider *slider = [[UISlider alloc]initWithFrame:CGRectMake(sliderX, sliderX, sliderW, sliderH)];
    slider.maximumValue = self.episode.PicCount;
    slider.minimumValue = 1;
    [slider addTarget:self action:@selector(jumpToPage:) forControlEvents:UIControlEventValueChanged];
    [self.bottomView addSubview:slider];
    
    CGFloat downloadW = 20;
    CGFloat downloadX = bottomView.frame.size.height - margin - downloadW;
    UIButton *download = [[UIButton alloc]initWithFrame:CGRectMake(downloadX, sliderX, downloadW, downloadW)];
    [download setImage:[UIImage imageNamed:@"iconfont-jieping"] forState:UIControlStateNormal];
    [download addTarget:self action:@selector(downloadImage) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:download];
    self.progressSlider = slider;
    
}

- (void)showAssistView
{
    CGRect newTop = self.topView.frame;
    CGRect newBottom = self.bottomView.frame;
    
    if (self.topView.frame.origin.x >= -0.000001f && self.topView.frame.origin.x <= 0.000001f) {
        newTop.origin.x = - newTop.size.width;
        newBottom.origin.x = Width + newBottom.size.width;
    }
    else
    {
        newTop.origin.x = 0;
        newBottom.origin.x = Width - newBottom.size.width;
    }
    [UIView animateWithDuration:0.4 animations:^{
        self.topView.frame = newTop;
        self.bottomView.frame = newBottom;
    }];
}

- (void)backPreviousVC
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)downloadImage
{
    [self showAssistView];
    UIGraphicsBeginImageContext(self.view.frame.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(viewImage,nil,nil,nil);
}

- (void)jumpToPage:(UISlider *)slider
{
    NSInteger page = (NSInteger)slider.value;
    if (page > self.pictureURLArray.count) {
        return;
    }
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:page - 1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.isAutoPageUp) {
        if (self.nextArray.count != 0 && self.pictureURLArray.count != 0) {
            return self.pictureURLArray.count + 1;
        }
    }
    return self.pictureURLArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    MHComicPictureCell *cell = [tableView dequeueReusableCellWithIdentifier:@"picture" forIndexPath:indexPath];
    if (self.isAutoPageUp) {
        if(self.nextArray.count != 0)
        {
            if (indexPath.row == self.pictureURLArray.count) {
                cell.pictureHeight = [self.nextArray firstObject];
            }
            else
            {
                cell.pictureHeight = self.pictureURLArray[indexPath.row];
            }
        }
        else
        {
            cell.pictureHeight = self.pictureURLArray[indexPath.row];
        }
    }
    else
        cell.pictureHeight = self.pictureURLArray[indexPath.row];
    __weak MHComicPictureViewController *test = self;
    cell.showAssistViewBlock = ^()
    {
        [test showAssistView];
    };
    self.comicSystemView.currentPage = indexPath.row;
    cell.pictureNum = [NSString stringWithFormat:@"%ld", indexPath.row];
    self.progressSlider.value = (float)indexPath.row;
    self.comicIntroduct.readPage = indexPath.row;
    self.comicIntroduct.readSection = self.episode.SectionName;
    self.comicIntroduct.readSectionIndex = self.index;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MHPisctureHeight *height = nil;
    if (self.isAutoPageUp) {
        if (self.nextArray.count != 0 && self.pictureURLArray.count != 0 && indexPath.row == self.pictureURLArray.count) {
            height = [self.nextArray lastObject];
        }
        else
            height = self.pictureURLArray[indexPath.row];
    }
    else
    {
        height = self.pictureURLArray[indexPath.row];
    }
    return height.pictureHeight + 10;
}

#pragma mark - 放大缩小
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    if ([scrollView isEqual:self.scrollView]) {
        return scrollView.subviews[0];
    }
    return nil;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    // 取出正在缩放的视图
    if ([scrollView isEqual:self.scrollView]) {
        if (scrollView.zoomScale < 1) {// 缩小
            self.tableView.center = self.scrollView.center;
        }
        else{// 放大
            self.tableView.center = CGPointMake(scrollView.contentSize.width / 2, scrollView.contentSize.height / 2);
            
        }
    }
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
{
    if (CGSizeEqualToSize(scrollView.contentSize, CGSizeZero)) {
        self.tableViewScrollHeight = self.tableView.contentSize.height;
    }
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    scrollView.contentSize = CGSizeMake(scrollView.contentSize.width, 0);
    self.tableView.contentSize = CGSizeMake(self.tableView.contentSize.width, self.tableViewScrollHeight + Width * (scale - 1) - Width * ((scale - 1) / 2));
}

#pragma mark - 自动翻章
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([scrollView isEqual:self.tableView]) {
        if (self.isAutoPageUp) {
            _newy= scrollView.contentOffset.y;
            if (_newy != _oldy && !self.isautoScroll) {
                if (_newy < _oldy) {// 上滑
                    if (self.previousArray.count != 0 )
                    {
                        self.isautoScroll = NO;
                        if (scrollView.contentOffset.y < 0)
                        {
                            self.episode = self.episodeArray[self.index + 1];
                            self.index = self.index + 1;
                            self.SectionName.text = self.episode.SectionName;
                            self.comicSystemView.episodeName = self.episode.SectionName;
                            self.comicSystemView.totalPage = self.episode.PicCount;
                            
                            self.nextArray = self.pictureURLArray;
                            self.pictureURLArray = self.previousArray;
                            self.previousArray = nil;
                            [self.tableView reloadData];
                            self.isautoScroll = YES;
                            MHPisctureHeight *height = [self.nextArray lastObject];
                            self.tableView.contentOffset = CGPointMake(0, self.tableView.contentSize.height - height.pictureHeight);
                            self.isautoScroll = NO;
                        }
                    }
                    else if (self.index != self.episodeArray.count - 1)
                    {
                        if (!self.isDownload) {
                            MHComicEpisode *episode = self.episodeArray[self.index + 1];
                            self.isDownload = YES;
                            if (episode.resource_id == 0) {
                                [self acquirePictureWith:episode];
                            }
                            else
                            {
                                [self acquireKonPictureWith:episode];
                            }
                        }
                    }
                    else
                    {
                        if (scrollView.contentOffset.y < 0) {
                            if (!self.isShowFirstPage) {
                                NSLog(@"没有上一页啦");
                                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
                                hud.mode = MBProgressHUDModeText;
                                hud.labelText = @"没有上一页啦";
                                hud.margin = 10.f;
                                hud.removeFromSuperViewOnHide = YES;
                                [hud hide:YES afterDelay:0.5];
                                self.isShowFirstPage = YES;
                            }
                        }
                    }
                    
                }else if(_newy > _oldy){// 下滑
                    if (self.nextArray.count != 0) {
                        self.isautoScroll = NO;
                        MHPisctureHeight *height = [self.nextArray lastObject];
                        if (scrollView.contentOffset.y > scrollView.contentSize.height - Width - height.pictureHeight) {
                            self.episode = self.episodeArray[self.index - 1];
                            self.SectionName.text = self.episode.SectionName;
                            self.comicSystemView.episodeName = self.episode.SectionName;
                            self.comicSystemView.totalPage = self.episode.PicCount;
                        }
                        if (scrollView.contentOffset.y > scrollView.contentSize.height - Width) {
                            self.index = self.index - 1;
                            
                            self.previousArray = self.pictureURLArray;
                            self.pictureURLArray = self.nextArray;
                            self.nextArray = nil;
                            self.progressSlider.value = 1.0f;
                            self.isautoScroll = YES;
                            [self.tableView reloadData];
                            self.tableView.contentOffset = CGPointMake(0, height.pictureHeight - Width);
                            self.isautoScroll = NO;
                            
                        }
                    }
                    else if (self.index != 0)
                    {
                        if (!self.isDownload) {
                            MHComicEpisode *episode = self.episodeArray[self.index - 1];
                            self.isDownload = YES;
                            if (episode.resource_id == 0) {
                                [self acquirePictureWith:episode];
                            }
                            else
                            {
                                [self acquireKonPictureWith:episode];
                            }
                        }
                    }
                    else
                    {
                        if (scrollView.contentOffset.y > scrollView.contentSize.height -  Width) {
                            if (!self.isShowLastPage) {
                                NSLog(@"没有下一页啦");
                                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
                                hud.mode = MBProgressHUDModeText;
                                hud.labelText = @"没有下一页啦";
                                hud.margin = 10.f;
                                hud.removeFromSuperViewOnHide = YES;
                                [hud hide:YES afterDelay:0.5];                                self.isShowLastPage = YES;
                            }
                        }
                    }
                }
                _oldy = _newy;
            }
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    MHDataManager *manager = [MHDataManager shareManager];
    if ([manager ComicIntroductHasInReadList:self.comicIntroduct]) {
        [manager updateReadListtWithComicIntroduct:self.comicIntroduct];
    }
    else
    {
        [manager insertReadListWithComicIntroduct:self.comicIntroduct];
    }
}

@end
